﻿using Microsoft.SharePoint;
using System;
using System.Collections.Generic;

namespace SP.FeatureAdministrationTool.FeatureManagerModule
{
    public class SiteCollectionFeatureManager : FeatureManager
    {
        private Guid siteCollectionId;

        public SiteCollectionFeatureManager(Guid siteCollectionId)
        {
            this.siteCollectionId = siteCollectionId;
        }

        public override void ActivateFeature(Guid featureId)
        {
            using (SPSite site = new SPSite(siteCollectionId)) // too many new instance
            {
                site.Features.Add(featureId);
            }
        }

        public override void DeactivateFeature(Guid featureId)
        {
            using (SPSite site = new SPSite(siteCollectionId))
            {
                site.Features.Remove(featureId);
            }
        }

        public override List<Feature> GetAllFeatures()
        {
            List<Feature> features = new List<Feature>();
            using (SPSite site = new SPSite(siteCollectionId))
            {
                foreach (Feature feature in this.GetFeatures(SPFeatureScope.Site))
                {
                    try
                    {
                        feature.Status = site.Features[feature.Id] == null ? FeatureActivationStatus.Deactivated : FeatureActivationStatus.Activated;
                        features.Add(feature);
                    }
                    catch
                    {
                    }
                }
            }

            return features;
        }
    }
}
